package com.wondream.plumelog.example.log4j2.filters;

import com.plumelog.core.util.StringUtils;
import com.wondream.plumelog.example.log4j2.constants.TraceConstants;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
 
/**
 * @Classname TraceIdFilter
 * @Description TraceId使用的过滤器
 * @Date 2021/8/16 10:07
 * @Created by gangye
 */
//@WebFilter(urlPatterns = "/*",filterName = "traceIdFilter")   //过滤器过滤路径可以在注解中配置，也可在后面的配置类中在代码中增加
public class TraceIdFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String traceId = request.getHeader(TraceConstants.TRACE_ID_HTTP_FIELD);
        String parentSpanId = request.getHeader(TraceConstants.PARENT_SPAN_ID_HTTP_FIELD);
        if (StringUtils.isNotEmpty(parentSpanId)){
            MDC.put(TraceConstants.PARENT_SPAN_ID_MDC_FIELD,parentSpanId);
        }
        String spanId = request.getHeader(TraceConstants.SPAN_ID_HTTP_FIELD);
        if (StringUtils.isEmpty(traceId)){
            traceId = UUID.randomUUID().toString().replace("-","").substring(0,16);
            spanId = traceId;
        }
        if (StringUtils.isEmpty(spanId)){
            spanId = UUID.randomUUID().toString().replace("-","").substring(0,16);
        }
        MDC.put(TraceConstants.TRACE_ID_MDC_FIELD, traceId);
        MDC.put(TraceConstants.SPAN_ID_MDC_FIELD, spanId);
 
        try {
            filterChain.doFilter(request,response);
        }finally {
            MDC.remove(TraceConstants.TRACE_ID_MDC_FIELD);
            MDC.remove(TraceConstants.SPAN_ID_MDC_FIELD);
            MDC.remove(TraceConstants.PARENT_SPAN_ID_MDC_FIELD);
        }
    }
}